﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.IO;
using Marbles.Core.Filters;

namespace Marbles.Core.Handlers
{
    class ContentCompressionModule : IHttpModuleBase
    {
        public string Name
        {
            get { return this.GetType().Name; }
        }

        public void Dispose()
        {
        }

        public void Init(HttpApplication context)
        {
            context.ReleaseRequestState += new EventHandler(ContentCompressionModule_CompressContent);
            context.PreSendRequestHeaders += new EventHandler(ContentCompressionModule_CompressContent);
        }

        public void ContentCompressionModule_CompressContent(object sender, EventArgs e)
        {
            string setting = Settings.SettingsManager.PageCompression;
            if (string.IsNullOrEmpty(setting)) {return;}
            setting = setting.ToLower();
            if ((string.IsNullOrEmpty(setting)) || (setting.ToLower() == "default")) { return; }

            HttpApplication application = sender as HttpApplication;
            if ((application == null) || (application.Context == null) || (application.Context.Items == null)) { return; }
            Page Page = application.Context.Handler as Page;
            if (Page == null) { return; }
            if (application.Response == null) { return; }
            if (application.Response.ContentType == null) { return; }
            if (application.Response.ContentType.ToLower() != "text/html") { return; }

            HttpResponseFilter filter = GetPreferredFilter(application.Request.Headers["Accept-Encoding"].ToLower().Split(','), application.Response.Filter, setting);
            if (filter != null)
            {
                application.Response.Filter = filter;
            }

        }

        public HttpResponseFilter GetPreferredFilter(string[] acceptencoding, Stream filter, string preferredtype)
        {
            HttpResponseFilter value = null;

            if (preferredtype == "whitespace") { return new WhiteSpaceResponseFilter(filter); }
            if ((preferredtype == "deflate") && acceptencoding.Contains<string>("deflate")) { return new DeflateResponseFilter(filter); }
            if ((preferredtype == "gzip") && acceptencoding.Contains<string>("gzip")) { return new GZipResponseFilter(filter); }

            return new WhiteSpaceResponseFilter(value);
        }
    }
}